// Wordfragment.kt
package com.example.sunchaodong

import android.os.Bundle
import android.view.*
import android.widget.Button
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView

class Wordfragment : Fragment(), WordAdapter.OnItemLongClickListener {

    private lateinit var wordAdapter: WordAdapter
    private lateinit var words: MutableList<String>
    private var selectedPosition: Int = -1
    private lateinit var wordFileHelper: WordFileHelper

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_word, container, false)
        wordFileHelper = WordFileHelper(requireContext())
        words = wordFileHelper.readWordsFromFile().toMutableList()
        wordAdapter = WordAdapter(words, this)
        val recyclerView: RecyclerView = view.findViewById(R.id.recyclerView)
        recyclerView.layoutManager = LinearLayoutManager(context)
        recyclerView.adapter = wordAdapter

        val homeButton: Button = view.findViewById(R.id.home_button)
        homeButton.setOnClickListener {
            (activity as? MainActivity)?.showMainActivityViews()
        }

        return view
    }

    override fun onItemLongClick(position: Int, view: View): Boolean {
        selectedPosition = position
        registerForContextMenu(view)
        view.showContextMenu()
        unregisterForContextMenu(view)
        return true
    }

    override fun onCreateContextMenu(menu: ContextMenu, v: View, menuInfo: ContextMenu.ContextMenuInfo?) {
        super.onCreateContextMenu(menu, v, menuInfo)
        menu.add(Menu.NONE, 1, Menu.NONE, "删除").setOnMenuItemClickListener {
            words.removeAt(selectedPosition)
            wordAdapter.notifyItemRemoved(selectedPosition)
            wordFileHelper.saveWordsToFile(words)
            true
        }
    }
}